package com.qf.zyh.web.controller;

import com.qf.zyh.common.Const;
import com.qf.zyh.util.StrUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (!StrUtils.empty(method)) {
            resp.sendRedirect("index.jsp");
            return;
        }
        try {
            Class<? extends BaseServlet> aClass = this.getClass();
            Method method1 = aClass.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            String invoke = (String) method1.invoke(this, req, resp);
            System.out.println(invoke+"inv");
            if (invoke!=null) {
                if (invoke.startsWith(Const.SysConst.FORWARD)) {
                    req.getRequestDispatcher(invoke.substring(invoke.indexOf(":")+1)).forward(req,resp);
                }else if (invoke.startsWith(Const.SysConst.REDIRECT)) {
                    resp.sendRedirect(req.getContextPath()+"/"+invoke.substring(invoke.indexOf(":")+1));
                }else {
                    PrintWriter writer = resp.getWriter();
                    writer.write(invoke);
                    writer.flush();
                    writer.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
